/*
 * BuyServlet.java
 * 作用：处理用户购买商品的请求，验证收货地址和商品所有权，并创建新的订单。
 */
package com.campustradingwall.controller;

import com.campustradingwall.dao.AddressDao;
import com.campustradingwall.dao.OrderDao;
import com.campustradingwall.dao.ProductDao;
import com.campustradingwall.model.Address;
import com.campustradingwall.model.Order;
import com.campustradingwall.model.Product;
import com.campustradingwall.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/buy")
public class BuyServlet extends HttpServlet {
    private ProductDao productDao = new ProductDao();
    private AddressDao addressDao = new AddressDao();
    private OrderDao orderDao = new OrderDao();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");

        // 检查用户是否填写了收货地址
        List<Address> addresses = addressDao.getAddressesByUserId(user.getId());
        if (addresses == null || addresses.isEmpty()) {
            // 如果没有地址，重定向到用户中心页面，并附带提示信息
            request.getSession().setAttribute("message", "请先填写您的收货地址后再购买！");
            response.sendRedirect(request.getContextPath() + "/user/profile");
            return;
        }
        
        // 检查购买的是否是自己的商品
        int productId = Integer.parseInt(request.getParameter("id"));
        Product product = productDao.getProductById(productId);
        if (product.getUserId() == user.getId()) {
            request.getSession().setAttribute("message", "您不能购买自己发布的商品！");
            response.sendRedirect(request.getContextPath() + "/product?id=" + productId);
            return;
        }

        // 创建订单
        Order order = new Order();
        order.setProductId(productId);
        order.setBuyerId(user.getId());
        order.setSellerId(product.getUserId());
        order.setStatus("pending"); // 初始状态为待处理

        orderDao.createOrder(order);

        // 重定向到"我的订单"页面，并显示成功提示
        request.getSession().setAttribute("message", "下单成功！请在'我发送的订单'中查看。");
        response.sendRedirect(request.getContextPath() + "/user/orders");
    }
} 